package com.example.myservlet;

import com.example.anno.RequestMapping;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@MultipartConfig
@RequestMapping("/upload")
public class UploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        Part file = req.getPart("file");          // <input type="file" name="file">
        String desc = req.getParameter("desc");   // 普通字段

        String fileName = Paths.get(file.getSubmittedFileName()).getFileName().toString();
        Path saveTo = Paths.get("uploads").resolve(fileName);
        Files.createDirectories(saveTo.getParent());
        try (InputStream in = file.getInputStream()) {
            Files.copy(in, saveTo, StandardCopyOption.REPLACE_EXISTING);
        }

        resp.setContentType("text/plain;charset=UTF-8");
        resp.getWriter().printf("upload ok: %s, desc=%s%n", fileName, desc);
    }
}